package cn.itcast.web.action;

import cn.itcast.utils.ResponseUtils;
import com.alibaba.fastjson.JSONArray;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.convention.annotation.*;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
@Actions
public class ImgsAction extends ActionSupport {
    private File imgFile;
    private String imgFileFileName;
    private String imgFileContentType;

    public void setImgFile(File imgFile) {
        this.imgFile = imgFile;
    }

    public void setImgFileFileName(String imgFileFileName) {
        this.imgFileFileName = imgFileFileName;
    }

    public void setImgFileContentType(String imgFileContentType) {
        this.imgFileContentType = imgFileContentType;
    }

    /*
        最终响应json数据到页面
        error : 0 成功    1 失败
        url: 图片有效路径
       */
    //uploadJson : '../../imgs_upload.action',
    @Action(value = "imgs_upload")
    public String upload() {

        //使用随机文件名 uuid
        UUID uuid = UUID.randomUUID();
        String ext = imgFileFileName.substring(imgFileFileName.lastIndexOf("."));//获取文件后缀名
        imgFileFileName = uuid + ext;
        //绝对路径
        // String realPath = ServletActionContext.getServletContext().getRealPath("/upload/");
        String realPath = "F://upload";
//        String savePath=ServletActionContext.getRequest().getContextPath()+"/upload/";
        String savePath = "/upload/";
        //复制文件到文件夹
        File destFile = new File(realPath + "/" + imgFileFileName);
        try {
            FileUtils.copyFile(imgFile, destFile);

        } catch (IOException e) {
            e.printStackTrace();
        }
        //响应json数据
        Map<String, Object> result = new HashMap<>();
        result.put("error", 0);
        result.put("url", savePath + imgFileFileName);
        String json = JSONArray.toJSONString(result);
        ResponseUtils.responseWriter(json);

        return NONE;
    }

    //fileManagerJson : '../../image_manage.action' 图片空间图片显示
    @Action(value = "image_manage", results = {@Result(name = "success", type = "json")})
    public String manage() {
        // 根目录路径，可以指定绝对路径，比如 d:/xxx/upload/xxx.jpg
        String rootPath = "F://upload/";
        // 根目录URL，可以指定绝对路径，比如 http://www.yoursite.com/attached/
        String rootUrl = "/upload/";

        // 遍历目录取的文件信息
        List<Map<String, Object>> fileList = new ArrayList<Map<String, Object>>();
        // 当前上传目录
        File currentPathFile = new File(rootPath);
        // 图片扩展名
        String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};

        if (currentPathFile.listFiles() != null) {
            for (File file : currentPathFile.listFiles()) {
                Map<String, Object> hash = new HashMap<String, Object>();
                String fileName = file.getName();
                if (file.isDirectory()) {
                    hash.put("is_dir", true);
                    hash.put("has_file", (file.listFiles() != null));
                    hash.put("filesize", 0L);
                    hash.put("is_photo", false);
                    hash.put("filetype", "");
                } else if (file.isFile()) {
                    String fileExt = fileName.substring(
                            fileName.lastIndexOf(".") + 1).toLowerCase();
                    hash.put("is_dir", false);
                    hash.put("has_file", false);
                    hash.put("filesize", file.length());
                    hash.put("is_photo", Arrays.<String>asList(fileTypes)
                            .contains(fileExt));
                    hash.put("filetype", fileExt);
                }
                hash.put("filename", fileName);
                hash.put("datetime",
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file
                                .lastModified()));
                fileList.add(hash);
            }
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("moveup_dir_path", "");
        result.put("current_dir_path", rootPath);
        result.put("current_url", rootUrl);
        result.put("total_count", fileList.size());
        result.put("file_list", fileList);
        ActionContext.getContext().getValueStack().push(result);

        return SUCCESS;
    }


}
